package com.ruoyi.easyExcelHandler.listener.logisticsTracking;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;

import com.ruoyi.logistics.domain.QcLogisticsTracking;
import com.ruoyi.logistics.service.IQcLogisticsTrackingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QcLogisticsTrackingListener implements ReadListener<QcLogisticsTracking> {

    private Logger log = LoggerFactory.getLogger(QcLogisticsTrackingListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5000;

    private IQcLogisticsTrackingService qcLogisticsTrackingService;
    /**
     * 缓存的数据
     */
    private List<QcLogisticsTracking> cachedDataList = new ArrayList<>();

    public QcLogisticsTrackingListener() {
    }

    /**
     * @param qcLogisticsTrackingService
     */
    public QcLogisticsTrackingListener(IQcLogisticsTrackingService qcLogisticsTrackingService) {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
        this.qcLogisticsTrackingService = qcLogisticsTrackingService;
    }

    public List<QcLogisticsTracking> getCachedDataList() {
        return cachedDataList;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(QcLogisticsTracking data, AnalysisContext context) {
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        // if (cachedDataList.size() >= BATCH_COUNT) {
        //     qrFbaCostService.importSetQrFbaCost(cachedDataList);
        //     // 存储完成清理 list
        //     cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        // }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        qcLogisticsTrackingService.importSetQcLogisticsTracking(cachedDataList);
        log.info("所有数据解析完成！");
    }

}
